<?php

namespace app\admin\controller\scanwork;

use app\common\controller\Backend;
use think\Db;

/**
 * 主动报工工资统计
 */
class ActiveWageStatistics extends Backend
{
    protected $noNeedLogin = [];
    protected $noNeedRight = [];

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 工资统计首页
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            $params = $this->request->get();
            
            $startDate = isset($params['start_date']) ? $params['start_date'] : date('Y-m-01');
            $endDate = isset($params['end_date']) ? $params['end_date'] : date('Y-m-d');
            $userId = isset($params['user_id']) ? $params['user_id'] : '';
            $wageType = isset($params['wage_type']) ? $params['wage_type'] : '';
            
            $where = [
                ['status', '=', 1], // 只统计已审核通过的
                ['work_date', 'between', [$startDate, $endDate]]
            ];
            
            if ($userId) {
                $where[] = ['user_id', '=', $userId];
            }
            
            // 查询工资统计数据
            $wageData = $this->getWageStatistics($where, $wageType);
            
            $result = [
                'code' => 1,
                'msg' => '获取成功',
                'data' => $wageData
            ];
            
            return json($result);
        }
        
        return $this->view->fetch();
    }

    /**
     * 获取工资统计数据
     */
    private function getWageStatistics($where, $wageType = '')
    {
        try {
            // 关联相关表查询，获取完整信息
            $query = Db::table('fa_scanwork_active_report')->alias('ar')
                ->join('fa_user u', 'ar.user_id = u.id', 'LEFT')
                ->join('fa_scanwork_order o', 'ar.order_id = o.id', 'LEFT')
                ->join('fa_scanwork_product p', 'ar.product_id = p.id', 'LEFT')
                ->join('fa_scanwork_model m', 'ar.model_id = m.id', 'LEFT')
                ->join('fa_scanwork_process pr', 'ar.process_id = pr.id', 'LEFT');
            
            // 应用查询条件
            foreach ($where as $condition) {
                if (count($condition) == 3) {
                    $query->where('ar.' . $condition[0], $condition[1], $condition[2]);
                }
            }
            
            $list = $query->field('
                    ar.id,
                    ar.user_id,
                    u.nickname as user_name,
                    u.username,
                    o.order_no,
                    p.name as product_name,
                    m.name as model_name,
                    pr.name as process_name,
                    ar.quantity,
                    ar.work_hours,
                    ar.piece_wage,
                    ar.time_wage,
                    ar.total_wage,
                    ar.work_date,
                    ar.start_time,
                    ar.end_time,
                    ar.audit_time,
                    ar.remark
                ')
                ->order('ar.work_date DESC, ar.id DESC')
                ->select();
            

            
            // 按员工分组统计
            $userStats = [];
            $totalStats = [
                'total_piece_wage' => 0,
                'total_time_wage' => 0,
                'total_wage' => 0,
                'total_quantity' => 0,
                'total_hours' => 0,
                'report_count' => 0
            ];
            
            foreach ($list as $item) {
                $userId = $item['user_id'];
                
                if (!isset($userStats[$userId])) {
                    $userStats[$userId] = [
                        'user_id' => $userId,
                        'user_name' => $item['user_name'] ?: ($item['username'] ?: '员工' . $userId),
                        'piece_wage' => 0,
                        'time_wage' => 0,
                        'total_wage' => 0,
                        'quantity' => 0,
                        'work_hours' => 0,
                        'report_count' => 0,
                        'reports' => []
                    ];
                }
                
                $userStats[$userId]['piece_wage'] += floatval($item['piece_wage']);
                $userStats[$userId]['time_wage'] += floatval($item['time_wage']);
                $userStats[$userId]['total_wage'] += floatval($item['total_wage']);
                $userStats[$userId]['quantity'] += intval($item['quantity']);
                $userStats[$userId]['work_hours'] += floatval($item['work_hours']);
                $userStats[$userId]['report_count']++;
                $userStats[$userId]['reports'][] = $item;
                
                // 总计
                $totalStats['total_piece_wage'] += floatval($item['piece_wage']);
                $totalStats['total_time_wage'] += floatval($item['time_wage']);
                $totalStats['total_wage'] += floatval($item['total_wage']);
                $totalStats['total_quantity'] += intval($item['quantity']);
                $totalStats['total_hours'] += floatval($item['work_hours']);
                $totalStats['report_count']++;
            }
            
            // 按工资类型筛选
            if ($wageType) {
                $filteredStats = [];
                foreach ($userStats as $userId => $userData) {
                    if ($wageType == 'piece' && $userData['piece_wage'] > 0) {
                        $filteredStats[$userId] = $userData;
                    } elseif ($wageType == 'time' && $userData['time_wage'] > 0) {
                        $filteredStats[$userId] = $userData;
                    }
                }
                $userStats = $filteredStats;
            }
            
            // 计算效率指标
            foreach ($userStats as &$userData) {
                $userData['efficiency'] = $userData['work_hours'] > 0 ? 
                    round($userData['quantity'] / $userData['work_hours'], 2) : 0;
                $userData['avg_wage_per_hour'] = $userData['work_hours'] > 0 ? 
                    round($userData['total_wage'] / $userData['work_hours'], 2) : 0;
                $userData['avg_wage_per_report'] = $userData['report_count'] > 0 ? 
                    round($userData['total_wage'] / $userData['report_count'], 2) : 0;
            }
            
            return [
                'user_stats' => array_values($userStats),
                'total_stats' => $totalStats,
                'detail_list' => $list
            ];
            
        } catch (\Exception $e) {
            trace('主动报工工资统计查询错误: ' . $e->getMessage(), 'error');
            return [
                'user_stats' => [],
                'total_stats' => [
                    'total_piece_wage' => 0,
                    'total_time_wage' => 0,
                    'total_wage' => 0,
                    'total_quantity' => 0,
                    'total_hours' => 0,
                    'report_count' => 0
                ],
                'detail_list' => []
            ];
        }
    }

    /**
     * 详细工资报表
     */
    public function detail()
    {
        if ($this->request->isAjax()) {
            $params = $this->request->get();
            
            $startDate = isset($params['start_date']) ? $params['start_date'] : date('Y-m-01');
            $endDate = isset($params['end_date']) ? $params['end_date'] : date('Y-m-d');
            $userId = isset($params['user_id']) ? $params['user_id'] : '';
            
            $where = [
                ['ar.status', '=', 1], // 只统计已审核通过的
                ['ar.work_date', 'between', [$startDate, $endDate]]
            ];
            
            if ($userId) {
                $where[] = ['ar.user_id', '=', $userId];
            }
            
            // 查询详细数据
            $query = Db::table('fa_scanwork_active_report')->alias('ar')
                ->join('fa_user u', 'ar.user_id = u.id', 'LEFT')
                ->join('fa_scanwork_order o', 'ar.order_id = o.id', 'LEFT')
                ->join('fa_scanwork_product p', 'ar.product_id = p.id', 'LEFT')
                ->join('fa_scanwork_model m', 'ar.model_id = m.id', 'LEFT')
                ->join('fa_scanwork_process pr', 'ar.process_id = pr.id', 'LEFT');
            
            foreach ($where as $condition) {
                if (count($condition) == 3) {
                    $query->where($condition[0], $condition[1], $condition[2]);
                }
            }
            
            $list = $query->field('
                    ar.id,
                    ar.user_id,
                    u.nickname as user_name,
                    u.username,
                    o.order_no,
                    p.name as product_name,
                    m.name as model_name,
                    pr.name as process_name,
                    ar.quantity,
                    ar.work_hours,
                    ar.piece_wage,
                    ar.time_wage,
                    ar.total_wage,
                    ar.work_date,
                    ar.start_time,
                    ar.end_time,
                    ar.audit_time,
                    ar.remark
                ')
                ->order('ar.work_date DESC, ar.id DESC')
                ->select();
            
            $result = [
                'code' => 1,
                'msg' => '获取成功',
                'data' => $list
            ];
            
            return json($result);
        }
        
        return $this->view->fetch();
    }

    /**
     * 导出工资统计数据
     */
    public function export()
    {
        $params = $this->request->get();
        
        $startDate = isset($params['start_date']) ? $params['start_date'] : date('Y-m-01');
        $endDate = isset($params['end_date']) ? $params['end_date'] : date('Y-m-d');
        $userId = isset($params['user_id']) ? $params['user_id'] : '';
        $wageType = isset($params['wage_type']) ? $params['wage_type'] : '';
        
        $where = [
            ['status', '=', 1], // 只统计已审核通过的
            ['work_date', 'between', [$startDate, $endDate]]
        ];
        
        if ($userId) {
            $where[] = ['user_id', '=', $userId];
        }
        
        // 查询详细数据
        $query = Db::table('fa_scanwork_active_report');
        
        // 应用查询条件
        foreach ($where as $condition) {
            if (count($condition) == 3) {
                $query->where($condition[0], $condition[1], $condition[2]);
            }
        }
        
        $list = $query->field('
                user_id,
                quantity,
                work_hours,
                piece_wage,
                time_wage,
                total_wage,
                work_date,
                start_time,
                end_time,
                audit_time,
                remark
            ')
            ->order('work_date DESC, id DESC')
            ->select();
        
        // 生成CSV文件
        $filename = '主动报工工资统计_' . date('YmdHis') . '.csv';
        header('Content-Type: text/csv; charset=utf-8');
        header('Content-Disposition: attachment; filename="' . $filename . '"');
        
        // 输出CSV头部
        echo "\xEF\xBB\xBF"; // UTF-8 BOM
        echo "员工ID,生产数量,工作时长(小时),计件工资,计时工资,总工资,工作日期,开始时间,结束时间,审核时间,备注\n";
        
        // 输出数据
        foreach ($list as $item) {
            $row = [
                $item['user_id'],
                $item['quantity'],
                $item['work_hours'],
                $item['piece_wage'],
                $item['time_wage'],
                $item['total_wage'],
                $item['work_date'],
                $item['start_time'],
                $item['end_time'],
                $item['audit_time'] ? date('Y-m-d H:i:s', $item['audit_time']) : '',
                $item['remark']
            ];
            echo implode(',', $row) . "\n";
        }
        
        exit;
    }

    /**
     * 导出详细工资报表
     */
    public function exportDetail()
    {
        $params = $this->request->get();
        
        $startDate = isset($params['start_date']) ? $params['start_date'] : date('Y-m-01');
        $endDate = isset($params['end_date']) ? $params['end_date'] : date('Y-m-d');
        $userId = isset($params['user_id']) ? $params['user_id'] : '';
        
        $where = [
            ['ar.status', '=', 1], // 只统计已审核通过的
            ['ar.work_date', 'between', [$startDate, $endDate]]
        ];
        
        if ($userId) {
            $where[] = ['ar.user_id', '=', $userId];
        }
        
        // 查询详细数据
        $query = Db::table('fa_scanwork_active_report')->alias('ar')
            ->join('fa_user u', 'ar.user_id = u.id', 'LEFT');
        
        foreach ($where as $condition) {
            if (count($condition) == 3) {
                $query->where($condition[0], $condition[1], $condition[2]);
            }
        }
        
        $list = $query->field('
                u.nickname as user_name,
                u.username,
                ar.quantity,
                ar.work_hours,
                ar.piece_wage,
                ar.time_wage,
                ar.total_wage,
                ar.work_date,
                ar.start_time,
                ar.end_time,
                ar.audit_time,
                ar.remark
            ')
            ->order('ar.work_date DESC, ar.id DESC')
            ->select();
        
        // 生成CSV文件
        $filename = '主动报工详细工资报表_' . date('YmdHis') . '.csv';
        header('Content-Type: text/csv; charset=utf-8');
        header('Content-Disposition: attachment; filename="' . $filename . '"');
        
        // 输出CSV头部
        echo "\xEF\xBB\xBF"; // UTF-8 BOM
        echo "员工姓名,用户名,生产数量,工作时长(小时),计件工资,计时工资,总工资,工作日期,开始时间,结束时间,审核时间,备注\n";
        
        // 输出数据
        foreach ($list as $item) {
            $row = [
                $item['user_name'] ?: $item['username'],
                $item['username'],
                $item['quantity'],
                $item['work_hours'],
                $item['piece_wage'],
                $item['time_wage'],
                $item['total_wage'],
                $item['work_date'],
                $item['start_time'],
                $item['end_time'],
                $item['audit_time'] ? date('Y-m-d H:i:s', $item['audit_time']) : '',
                $item['remark']
            ];
            echo implode(',', $row) . "\n";
        }
        
        exit;
    }

    /**
     * 获取员工列表
     */
    public function getUsers()
    {
        $users = Db::table('fa_scanwork_active_report')
            ->where('status', 1)
            ->group('user_id')
            ->column('user_id');
        
        $userList = [];
        foreach ($users as $userId) {
            $userList[] = [
                'id' => $userId,
                'name' => '员工' . $userId
            ];
        }
        
        return json(['code' => 1, 'data' => $userList]);
    }

    /**
     * 测试方法
     */
    public function test()
    {
        try {
            // 检查表是否存在
            $tableExists = Db::query("SHOW TABLES LIKE 'fa_scanwork_active_report'");
            echo "表 fa_scanwork_active_report 存在: " . (empty($tableExists) ? '否' : '是') . "\n";
            
            if (!empty($tableExists)) {
                // 检查记录数
                $totalCount = Db::table('fa_scanwork_active_report')->count();
                echo "总记录数: {$totalCount}\n";
                
                // 检查已审核记录数
                $approvedCount = Db::table('fa_scanwork_active_report')->where('status', 1)->count();
                echo "已审核记录数: {$approvedCount}\n";
                
                // 检查时间范围内的记录
                $startDate = '2025-08-01';
                $endDate = '2025-08-04';
                $dateCount = Db::table('fa_scanwork_active_report')
                    ->where('status', 1)
                    ->where('work_date', 'between', [$startDate, $endDate])
                    ->count();
                echo "时间范围内({$startDate} 到 {$endDate})已审核记录数: {$dateCount}\n";
                
                // 显示前几条记录
                $records = Db::table('fa_scanwork_active_report')
                    ->where('status', 1)
                    ->limit(3)
                    ->select();
                echo "前3条已审核记录:\n";
                foreach ($records as $record) {
                    echo "ID: {$record['id']}, 用户ID: {$record['user_id']}, 工作日期: {$record['work_date']}, 总工资: {$record['total_wage']}\n";
                }
            }
            
        } catch (\Exception $e) {
            echo "错误: " . $e->getMessage() . "\n";
        }
    }
} 